package MEET.src.View;

import MEET.src.code.UserDao;

import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import java.awt.*;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.Date;

public class FreeMeetingRooms extends JFrame {
    private JTable table;
    private DefaultTableModel tableModel;
    private JComboBox<String> dateSelector; // 日期选择器
    private JComboBox<String> meetingRoomIdFilter;
    private JComboBox<String> campusFilter;
    private JComboBox<String> locationFilter;
    private JComboBox<String> roomNumberFilter;
    private JComboBox<String> capacityFilter;

    public FreeMeetingRooms() {
        initComponents();
        refreshTable();
    }

    private JPanel createHeaderPanel() {
        JPanel headerPanel = new JPanel();
        headerPanel.setBackground(new Color(0, 125, 153));
        headerPanel.setPreferredSize(new Dimension(830, 50));

        JLabel lblTitle = new JLabel("上海电力大学会议预订系统");
        lblTitle.setForeground(Color.WHITE);
        lblTitle.setFont(new Font("微软雅黑", Font.BOLD, 20));

        headerPanel.add(lblTitle);
        return headerPanel;
    }

    private void initComponents() {
        setTitle("空闲会议室查询");
        setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); // 设置关闭操作为隐藏窗口
        setLocationRelativeTo(null);
        Container contentPane = getContentPane();
        contentPane.setLayout(new BorderLayout());

        // --- 创建标题面板 ---
        JPanel headerPanel = createHeaderPanel();
        contentPane.add(headerPanel, BorderLayout.NORTH);

        // --- 创建背景面板 ---
        JPanel backgroundPanel = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                // 绘制背景图片
                ImageIcon backgroundIcon = new ImageIcon("D:\\java\\untitledJF\\src\\main\\resource\\images\\background2.jpg");
                Image scaledImage = backgroundIcon.getImage().getScaledInstance(830, 400, Image.SCALE_SMOOTH);
                g.drawImage(scaledImage, 0, 0, this);
            }
        };
        backgroundPanel.setLayout(null); // 使用绝对布局
        backgroundPanel.setOpaque(true); // 设置背景面板不透明
        contentPane.add(backgroundPanel, BorderLayout.CENTER);

        // --- 创建表格并将其置于背景之上 ---
        tableModel = new DefaultTableModel(
                new Object[][] {},
                new String[] {
                        "会议室ID", "校区", "地点", "房间号", "容纳量"
                }
        );
        table = new JTable(tableModel);
        table.setOpaque(false); // 设置表格透明
        table.setGridColor(new Color(200, 200, 200)); // 设置网格线颜色
        table.setShowGrid(true); // 显示网格线
        table.setShowHorizontalLines(true);
        table.setShowVerticalLines(true);

        // 设置表格字体
        table.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        table.getTableHeader().setFont(new Font("微软雅黑", Font.BOLD, 14));

        // 设置表格标题行颜色
        JTableHeader tableHeader = table.getTableHeader();
        tableHeader.setBackground(new Color(70, 130, 180));
        tableHeader.setForeground(Color.WHITE);

        JScrollPane scrollPane1 = new JScrollPane(table);
        scrollPane1.setOpaque(false); // 设置滚动面板透明
        scrollPane1.getViewport().setOpaque(false);
        scrollPane1.setBounds(10, 100, 800, 200);
        backgroundPanel.add(scrollPane1); // 将表格置于背景之上

        // --- 设置表格的蓝白交替填充色和文字居中 ---
        DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
        centerRenderer.setHorizontalAlignment(JLabel.CENTER);
        centerRenderer.setBackground(new Color(240, 248, 255)); // 浅蓝色背景
        centerRenderer.setForeground(new Color(50, 50, 50)); // 深色文字
        centerRenderer.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        table.setDefaultRenderer(Object.class, centerRenderer);

        // --- 创建日期选择器 ---
        dateSelector = new JComboBox<>();
        Date currentDate = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        for (int i = 0; i < 7; i++) { // 显示未来七天
            Date date = new Date(currentDate.getTime() + i * 24 * 60 * 60 * 1000);
            dateSelector.addItem(sdf.format(date));
        }

        // --- 创建刷新按钮 ---
        JButton refreshButton = new JButton("刷新");
        refreshButton.addActionListener(e -> refreshTable());
        refreshButton.setBackground(new Color(70,130,180));
        refreshButton.setForeground(Color.white);

        // --- 创建顶部面板用于放置日期选择器和刷新按钮 ---
        JPanel topPanel = new JPanel();
        topPanel.setLayout(new FlowLayout(FlowLayout.LEFT)); // 左对齐
        topPanel.add(new JLabel("选择日期:")); // 添加文字说明
        topPanel.add(dateSelector);
        topPanel.add(refreshButton);
        topPanel.setOpaque(false); // 设置面板透明
        topPanel.setBounds(20, 10, 830, 30); // 调整位置和大小
        backgroundPanel.add(topPanel); // 将顶部面板置于背景之上

        // --- 创建筛选框的表头 ---
        createFilterHeader(backgroundPanel);

        // --- 设置窗口大小 ---
        setSize(830, 400);
        setLocationRelativeTo(null);
    }

    private void createFilterHeader(JPanel backgroundPanel) {
        // 创建一个面板来包含筛选框
        JPanel filterPanel = new JPanel();
        filterPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
        filterPanel.setOpaque(false);

        // 获取筛选选项
        String[] meetingRoomIds = getMeetingRoomIdsFromDB();
        String[] campuses = getCampusesFromDB();
        String[] locations = getLocationsFromDB();
        String[] roomNumbers = getRoomNumbersFromDB();
        String[] capacities = getCapacitiesFromDB();

        // 创建筛选框
        meetingRoomIdFilter = new JComboBox<>(meetingRoomIds);
        campusFilter = new JComboBox<>(campuses);
        locationFilter = new JComboBox<>(locations);
        roomNumberFilter = new JComboBox<>(roomNumbers);
        capacityFilter = new JComboBox<>(capacities);

        // 添加到筛选面板
        filterPanel.add(new JLabel("会议室ID:"));
        filterPanel.add(meetingRoomIdFilter);
        filterPanel.add(new JLabel("校区:"));
        filterPanel.add(campusFilter);
        filterPanel.add(new JLabel("地点:"));
        filterPanel.add(locationFilter);
        filterPanel.add(new JLabel("房间号:"));
        filterPanel.add(roomNumberFilter);
        filterPanel.add(new JLabel("容纳量:"));
        filterPanel.add(capacityFilter);

        // 将筛选面板添加到背景面板，在表格上方
        filterPanel.setBounds(20, 50, 800, 30);
        backgroundPanel.add(filterPanel);
    }

    private String[] getMeetingRoomIdsFromDB() {
        // 这里应该从数据库中获取会议室ID列表
        // 示例数据
        return new String[]{"全部会议室", "001", "002", "003", "004", "005","006","007","008","009","010",
                "011","012","013","014","015"};
    }

    private String[] getCampusesFromDB() {
        // 这里应该从数据库中获取校区列表
        // 示例数据
        return new String[]{"全部校区", "临港", "杨浦"};
    }

    private String[] getLocationsFromDB() {
        // 这里应该从数据库中获取地点列表
        // 示例数据
        return new String[]{"全部地点", "二号教学楼", "杨浦报告厅", "杨浦会议厅", "学术楼", "1号教学楼","红楼","经外楼"};
    }

    private String[] getRoomNumbersFromDB() {
        // 这里应该从数据库中获取房间号列表
        // 示例数据
        return new String[]{"全部房间号", "101", "105","107","201","208","305","401","414", "506", "403", "204",
                "305","503"};
    }

    private String[] getCapacitiesFromDB() {
        // 这里应该从数据库中获取容纳量列表
        // 示例数据
        return new String[]{"全部容纳量","30","50","60","200", "55", "80", "100", "110", "115"};
    }

    private void refreshTable() {
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;

        try {
            // 加载数据库驱动程序
            conn = UserDao.getConnection();
            // 创建Statement对象
            stmt = conn.createStatement();

            // 获取选择的日期
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String selectedDate = (String) dateSelector.getSelectedItem();
            String startDate = selectedDate + " 00:00:00";
            String endDate = selectedDate + " 23:59:59";

            // 获取筛选条件
            String selectedMeetingRoomId = (String) meetingRoomIdFilter.getSelectedItem();
            String selectedCampus = (String) campusFilter.getSelectedItem();
            String selectedLocation = (String) locationFilter.getSelectedItem();
            String selectedRoomNumber = (String) roomNumberFilter.getSelectedItem();
            String selectedCapacity = (String) capacityFilter.getSelectedItem();

            // 构建查询语句
            String query = buildQuery(selectedDate, selectedMeetingRoomId, selectedCampus, selectedLocation, selectedRoomNumber, selectedCapacity);

            rs = stmt.executeQuery(query);

            // 清空表格模型
            tableModel.setRowCount(0);

            // 填充表格模型
            while (rs.next()) {
                Object[] row = {
                        rs.getString("CID"),
                        rs.getString("Carea"),
                        rs.getString("Clocation"),
                        rs.getString("Room"),
                        rs.getString("Capacity")
                };
                tableModel.addRow(row);
            }

            // 设置表格的蓝白交替填充色
            for (int i = 0; i < table.getRowCount(); i++) {
                for (int j = 0; j < table.getColumnCount(); j++) {
                    Component c = table.prepareRenderer(table.getCellRenderer(i, j), i, j);
                    if (i % 2 == 0) {
                        c.setBackground(new Color(240, 248, 255)); // 浅蓝色
                    } else {
                        c.setBackground(new Color(255, 255, 250)); // 奶白色
                    }
                    c.setForeground(new Color(50, 50, 50)); // 深色文字
                }
            }

        } catch (SQLException ex) {
            ex.printStackTrace();
        } finally {
            try {
                if (rs != null) rs.close();
                if (stmt != null) stmt.close();
                if (conn != null) conn.close();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }
    }

    private String buildQuery(String selectedDate, String selectedMeetingRoomId, String selectedCampus, String selectedLocation, String selectedRoomNumber, String selectedCapacity) {
        StringBuilder queryBuilder = new StringBuilder();
        queryBuilder.append("SELECT c.CID, c.Carea, c.Clocation, c.Room, c.Capacity ");
        queryBuilder.append("FROM schoolmeeting.conference c ");
        queryBuilder.append("WHERE c.CID NOT IN (");
        queryBuilder.append("    SELECT DISTINCT m.CID ");
        queryBuilder.append("    FROM schoolmeeting.meeting m ");
        queryBuilder.append("    WHERE m.Mstarttime >= '" + selectedDate + " 00:00:00' AND m.Mstarttime <= '" + selectedDate + " 23:59:59'");
        queryBuilder.append(") AND c.CID IN (SELECT CID FROM schoolmeeting.conference WHERE Capacity > 0)");

        // 添加筛选条件
        if (!"全部会议室".equals(selectedMeetingRoomId)) {
            queryBuilder.append(" AND c.CID = '" + selectedMeetingRoomId + "'");
        }
        if (!"全部校区".equals(selectedCampus)) {
            queryBuilder.append(" AND c.Carea = '" + selectedCampus + "'");
        }
        if (!"全部地点".equals(selectedLocation)) {
            queryBuilder.append(" AND c.Clocation = '" + selectedLocation + "'");
        }
        if (!"全部房间号".equals(selectedRoomNumber)) {
            queryBuilder.append(" AND c.Room = '" + selectedRoomNumber + "'");
        }
        if (!"全部容纳量".equals(selectedCapacity)) {
            queryBuilder.append(" AND c.Capacity = " + selectedCapacity);
        }

        return queryBuilder.toString();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            FreeMeetingRooms frame = new FreeMeetingRooms();
            frame.setVisible(true);
        });
    }

    }


